import { showConfirmDialog, showFailToast } from 'vant';
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { deserialize } from '@/plugins/reflect-metadata';
import useUserStore from '@/stores/user.store';

import { lunchAuth } from '../api';
import { RealAuthType } from '../const';
import { RealAuthConfig, RealAuthLunchRes } from '../models/RealAuth';

const useRealAuth = () => {
  const form = ref({
    validate: () => Promise.resolve(),
  });
  const router = useRouter();
  const userStore = useUserStore();
  const params = ref<RealAuthConfig>(new RealAuthConfig());

  const pageState = ref({
    isRealAuth: false,
    loading: false,
    checked: false,
  });

  const handleUpdate = async () => {
    try {
      pageState.value.loading = true;
      if (!pageState.value.checked) {
        showFailToast('请先阅读并同意《实名认证协议》');
        return;
      }
      await form.value.validate();
      const { data } = await lunchAuth(params.value);
      const resultData = deserialize(data.data, RealAuthLunchRes);
      if (resultData.certifyUrl) {
        showConfirmDialog({
          title: '实名认证',
          message: '是否前往实名认证页面？',
          confirmButtonText: '前往',
          cancelButtonText: '取消',
        }).then(() => {
          window.location.href = resultData.certifyUrl;
        });
      }
    } catch (error) {
      //
    } finally {
      pageState.value.loading = false;
    }
  };

  // 加载script  https://o.alicdn.com/yd-cloudauth/cloudauth-cdn/jsvm_all.js
  const handleInit = () => new Promise((resolve) => {
    const script = document.createElement('script');
    script.src = 'https://o.alicdn.com/yd-cloudauth/cloudauth-cdn/jsvm_all.js';
    script.onload = () => {
      resolve(true);
    };
    document.body.appendChild(script);
  });

  onMounted(async () => {
    pageState.value.isRealAuth = userStore.userInfo.realFlag === RealAuthType.已实名;
    if (pageState.value.isRealAuth) {
      router.replace({ name: 'RealAuthInfo' });
    }
    const isInit = await handleInit();
    if (isInit) {
      try {
        // @ts-ignore
        const metaInfo = window.getMetaInfo();
        if (metaInfo) {
          params.value.metaInfo = metaInfo;
          // eslint-disable-next-line no-console
          console.log(metaInfo);
        }
        if (!metaInfo) throw new Error();
      } catch (error) {
        showFailToast('设备信息获取失败');
      }
    } else {
      showFailToast('设备信息获取失败');
    }
  });

  return {
    form,
    params,
    pageState,
    handleUpdate,
  };
};

export default useRealAuth;
